/*
 * Copyright 2016-2017 lei.xu<xulei2008xulei@163.com>.
 *  
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.san21go.jfinfunc.time;

import org.san21go.jfinfunc.AbstractFunction;
import org.san21go.jfinfunc.FinFuncRuntimeException;
import org.san21go.jfinfunc.util.DateUtil;

/**
 * 计算天数、 月或两个日期之间的年数。 DATEDIF(start_date,end_date,unit)
 * 
 * @author xulei
 *
 */
public class DATEDIF extends AbstractFunction<Integer> {

	private String start_date;
	private String end_date;
	private String unit;

	public DATEDIF(String start_date, String end_date, String unit) {
		super();
		this.start_date = start_date;
		this.end_date = end_date;
		this.unit = unit;
	}

	@Override
	public Integer evaluate() throws FinFuncRuntimeException {
		if (DateUtil.isAfter(start_date, end_date)) {
			throw new RuntimeException("起始日不能大于结束日");
		}

		unit = unit.toUpperCase();

		int ret = 0;
		if ("Y".equals(unit)) {
			ret = DateUtil.diffYear(end_date, start_date);
		} else if ("M".equals(unit)) {
			ret = DateUtil.diffMonth(end_date, start_date);
		} else if ("D".equals(unit)) {
			ret = DateUtil.diffDate(end_date, start_date);
		} else if ("MD".equals(unit)) {
			throw new UnsupportedOperationException(String.format("unit参数：%s 暂不受支持", unit));
		} else if ("YM".equals(unit)) {
			throw new UnsupportedOperationException(String.format("unit参数：%s 暂不受支持", unit));
		} else if ("YD".equals(unit)) {
			throw new UnsupportedOperationException(String.format("unit参数：%s 暂不受支持", unit));
		} else {
			throw new UnsupportedOperationException(String.format("unit参数：%s 非法", unit));
		}
		return ret;
	}

}
